package com.sunwayworld.basemodule.rm.client.io;

import com.sunwayworld.baseline.framework.utils.TemplateExcelHelper;
import com.sunwayworld.basemodule.basedata.exporttemplate.service.LimsGenericTemplateService;
import com.sunwayworld.basemodule.rm.client.service.LimsClientService;
import com.sunwayworld.cloud.module.item.admarea.bean.CoreAdmAreaBean;
import com.sunwayworld.cloud.module.item.admarea.service.CoreAdmAreaService;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import org.apache.poi.hssf.usermodel.HSSFDataValidation;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddressList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component(value = "LimsClientExportTemplate")
@GikamBean
public class LimsClientExportTemplate implements LimsGenericTemplateService<String> {

    @Autowired
    @Lazy
    CoreAdmAreaService admAreaService;

    @Autowired
    @Lazy
    LimsClientService limsClientService;

    // 标题行所在索引
    private static final int titleRowIndex = 1;

    @Override
    public void initTemplateData(Path path, String id) {
        try {
            InputStream in = new FileInputStream(path.toString());
            Workbook workBook = WorkbookFactory.create(in);
            Sheet sheet = workBook.getSheetAt(0);

            // 客户类型，区域为系统编码
            String[] columns = new String[]{"clientType", "largeArea"};
            String[] codeCategoryIds = new String[]{"customerType", "largeArea"};
            TemplateExcelHelper.fillSheetSelect(sheet, titleRowIndex, columns, codeCategoryIds);

            // 自定义下拉选，省份
            Map<String, List<String>> paramMap = new HashMap<>();
            List<CoreAdmAreaBean> provices = admAreaService.selectListByFilter(SearchFilter.instance()
                .match("PARENTID", null).filter(MatchPattern.EQ));
            paramMap.put("province", provices.stream().map(CoreAdmAreaBean::getAdmAreaName).collect(Collectors.toList()));
            fillDropDown(sheet, titleRowIndex, paramMap);
            in.close();
            FileOutputStream outputStream = new FileOutputStream(path.toString());
            workBook.write(outputStream);
            outputStream.close();
            workBook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 根据下拉内容填充下拉框（可以是非选择内容）
     * @param sheet
     * @param rowIndex      标题行
     * @param selectListMap 填充的数据
     */
    public static void fillDropDown(Sheet sheet, int rowIndex, Map<String, List<String>> selectListMap) {
        int endRowNum = sheet.getPhysicalNumberOfRows()-1;
        Row firstRow = sheet.getRow(rowIndex);
        int endCellNum = firstRow.getPhysicalNumberOfCells();
        //获取列信息：
        String[] columnNames = new String[endCellNum];
        for (int i = 0; i < endCellNum; i++) {
            Cell cell = firstRow.getCell(i);
            if (cell != null) {
                if (cell.getCellComment() != null) {
                    columnNames[i] = cell.getCellComment().getString().getString();
                } else {
                    columnNames[i] = "";
                }
            } else {
                columnNames[i] = "";
            }
        }
        //设置下拉框
        for (int i = 0; i < columnNames.length; i++) {
            String columnName = columnNames[i];
            if (selectListMap.containsKey(columnName)) {
                String[] strs = selectListMap.get(columnName).toArray(new String[0]);
                DataValidationHelper helper = sheet.getDataValidationHelper();
                DataValidationConstraint constraint = helper.createExplicitListConstraint(strs);
                //参数顺序：开始行、结束行、开始列、结束列
                CellRangeAddressList regions = new CellRangeAddressList(endRowNum, endRowNum + 300, i, i);
                DataValidation validation = helper.createValidation(constraint, regions);
                //适配xls和xlsx
                if (validation instanceof HSSFDataValidation) {
                    validation.setSuppressDropDownArrow(false);
                } else {
                    validation.setSuppressDropDownArrow(true);
                    validation.setShowErrorBox(true);
                }
                sheet.addValidationData(validation);
            }
        }
    }

}
